package cn.icanci.loopstack.plugin.dalgen.engine;

import cn.icanci.loopstack.plugin.dalgen.config.GlobalConfig;
import cn.icanci.loopstack.plugin.dalgen.engine.impl.CustomEngineProxy;
import cn.icanci.loopstack.plugin.dalgen.engine.impl.DefaultEngine;
import cn.icanci.loopstack.plugin.dalgen.factory.ClassInfoFactory;
import cn.icanci.loopstack.plugin.dalgen.model.ClassInfoVO;
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.TemplateExceptionHandler;

import java.util.List;
import java.util.Locale;

/**
 * 抽象执行引擎
 * 
 * @author icanci
 * @since 1.0 Created in 2022/05/13 18:50
 */
public abstract class AbstractGeneralEngine implements GeneralEngine {

    private static Configuration configuration;

    /***
     * 获取FreeMaker创建模板
     */
    public static Configuration getConfiguration() {
        if (configuration == null) {
            configuration = new Configuration(Configuration.VERSION_2_3_23);
            try {
                configuration.setTemplateLoader(new ClassTemplateLoader(AbstractGeneralEngine.class, "/templates/"));
                configuration.setNumberFormat("#");
                configuration.setClassicCompatible(true);
                configuration.setDefaultEncoding("UTF-8");
                configuration.setLocale(Locale.CHINA);
            } catch (Exception e) {
                e.printStackTrace();
            }
            configuration.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
        }
        return configuration;
    }

    @Override
    public synchronized void execute(String path) {
        String dbModule = GlobalConfig.getGobleConfig(path).getDbModule();
        List<ClassInfoVO> classInfos = ClassInfoFactory.getClassInfoList();
        for (ClassInfoVO classInfo : classInfos) {
            genEntity(classInfo);
            // genMapstructEntity(classInfo);
            genRepositoryClass(classInfo);
            genRepositoryXml(classInfo, dbModule);
            // genMapstructClass(classInfo, dbModule);
        }

        System.out.println(GlobalConfig.getGobleConfig().getProjectPath() + " Build Complete.");

        // 执行自定义拦截接口 执行
        System.out.println("=== Begin To Execute Custom Module... ===");
        CustomEngineProxy.handleCustom();
        System.out.println("=== End To Execute Custom Module... ===");
    }

    /***
     * 初始化工程
     * 加载配置文件, 加载数据库连接, 加载数据表字段信息, 加载FreeMaker模板
     * 获得执行器
     */
    public static AbstractGeneralEngine init(String path) {
        return new DefaultEngine(path);
    }

}
